package st.business.tepth.business.taskallocation.detail;

import android.support.annotation.Nullable;
import android.util.SparseArray;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;

import st.business.tepth.R;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.post.TaskAllocation;
import st.business.tepth.business.bean.post.TaskAllocationDetail;
import st.business.tepth.config.ItemFields;
import st.shadow.library.core.util.utilcode.util.StringUtils;
import st.shadow.library.ui.recycler.MultipleItemEntity;

/**
 * @author zhangyu
 * @date 2019/2/23
 */
public class AllocationDetailAdapter extends BaseMultiItemQuickAdapter<MultipleItemEntity, BaseViewHolder> {
    public static final int TYPE_0 = 0;
    public static final int TYPE_1 = 1;
    public static final int TYPE_2 = 2;
    private List<MultipleItemEntity> mCheckedList = new ArrayList<>();
    private int mOldCheckPosition = -1;
    private OnCancelListener mListener;
    private OnItemChooseListener<Integer> mAddOtherListener;

    /**
     * Same as QuickAdapter#QuickAdapter(Context,int) but with
     * some initialization data.
     *
     * @param data A new list is created out of this one to avoid mutable list
     */
    public AllocationDetailAdapter(List<MultipleItemEntity> data,
                                   OnCancelListener listener,
                                   OnItemChooseListener<Integer> addOtherListener) {
        super(data);
        addItemType(TYPE_0, R.layout.item_allocation_detail_type_0);
        addItemType(TYPE_1, R.layout.item_allocation_detail_type_1);
        addItemType(TYPE_2, R.layout.item_allocation_detail_type_2);
        mListener = listener;
        mAddOtherListener = addOtherListener;
    }


    @Override
    protected void convert(final BaseViewHolder helper, final MultipleItemEntity item) {
        switch (item.getItemType()) {
            case TYPE_0:
                helper.setText(R.id.tv_classification,
                        (CharSequence) item.getField(ItemFields.ITEM_CONSTANT));
                helper.getView(R.id.tv_other_person).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mAddOtherListener != null) {
                            mAddOtherListener.onChoose(helper.getAdapterPosition());
                        }
                    }
                });
                break;
            case TYPE_1:
                helper.setChecked(R.id.check_person, (Boolean) item.getField("checked"));
                helper.getView(R.id.layout_checkbox).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean isChecked = item.getField("checked");
                        helper.setChecked(R.id.check_person, !isChecked);
                        item.setField("checked", !isChecked);
                        if (!isChecked) {
                            mCheckedList.add(item);
                        } else {
                            mCheckedList.remove(item);
                        }
                        if (mOldCheckPosition != helper.getAdapterPosition()) {
                            if (item.getField("isFinish")) {
                                //竣检项
                                MultipleItemEntity oldCheck = getItem(mOldCheckPosition);
                                if (oldCheck != null) {
                                    oldCheck.setField("checked", false);
                                    notifyItemChanged(mOldCheckPosition);
                                    mCheckedList.remove(oldCheck);
                                }
                                mOldCheckPosition = helper.getAdapterPosition();
                            }
                        }
                    }
                });
                TaskAllocationDetail.Person personBean = item.getField(ItemFields.ITEM_OBJ);
                // boolean isFinish = item.getField("isFinish");
                boolean cancelable = item.getField("cancelable");
                if (cancelable) {
                    helper.setEnabled(R.id.check_person, false);
                    helper.getView(R.id.layout_checkbox).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mListener != null) {
                                mListener.onCancel(item, helper.getAdapterPosition());
                            }
                        }
                    });
                } else {
                    helper.setEnabled(R.id.check_person, true);
                }
                helper.setText(R.id.check_person, personBean.getUser_name());
                break;
            case TYPE_2:
                helper.setText(R.id.tv_trouble, (CharSequence) item.getField(ItemFields.ITEM_CONSTANT));
                break;
        }
    }

    public String getCheckedList() {
        int finishCheck = 0;
        if (mCheckedList != null && !mCheckedList.isEmpty()) {
            SparseArray<List<Integer>> map = new SparseArray<>();
            List<TaskAllocation> allocations = new ArrayList<>();
            for (MultipleItemEntity entity : mCheckedList) {
                if (entity.getField("isFinish")) {
                    //竣检不能多选
                    finishCheck++;
                }
                TaskAllocationDetail.Person personBean = entity.getField(ItemFields.ITEM_OBJ);
                if (personBean != null) {
                    List<Integer> personIds = map.get((Integer) entity.getField("classId"));
                    if (personIds == null) {
                        personIds = new ArrayList<>();
                        map.put((Integer) entity.getField("classId"), personIds);
                    }
                    personIds.add(personBean.getId());
                }
            }
            for (int i = 0, size = map.size(); i < size; i++) {
                int id = map.keyAt(i);
                List<Integer> task_user_id = map.get(id);
                Object[] array = task_user_id.toArray();
                if (array != null) {
                    allocations.add(new TaskAllocation(id, StringUtils.join(array,
                            ',', 0, array.length)));
                }
            }
            if (finishCheck > 1) {
                return "竣检员不能选多个!";
            }
            return JSON.toJSONString(allocations);
        } else {
            return null;
        }
    }

    @Override
    public void setNewData(@Nullable List<MultipleItemEntity> data) {
        super.setNewData(data);
        if (data != null) {
            int i = 0;
            for (MultipleItemEntity entity : data) {
                if (entity.getItemType() == TYPE_1) {
                    if (entity.getField("checked")) {
                        mCheckedList.add(entity);
                        if (entity.getField("isFinish")) {
                            //记录竣检默认选择位置
                            mOldCheckPosition = i;
                        }
                    }
                }
                i++;
            }
        }
    }

    public void addNewData(int position, List<MultipleItemEntity> list) {
        MultipleItemEntity classification = getItem(position);
        if (classification != null) {
            List<Integer> personIdList =
                    classification.getField("personIdList");
            int classId = classification.getField("id");
            List<Integer> filterPerson = new ArrayList<>();
            List<MultipleItemEntity> filterItem = new ArrayList<>();
            for (MultipleItemEntity entity : list) {
                TaskAllocationDetail.Person personBean = entity.getField(ItemFields.ITEM_OBJ);
                if (!personIdList.contains(personBean.getId())) {
                    entity.setField("classId", classId);
                    filterPerson.add(personBean.getId());
                    mCheckedList.add(entity);
                    filterItem.add(entity);
                }
            }
            personIdList.addAll(filterPerson);
            if (!filterItem.isEmpty()) {
                addData(position + 1, filterItem);
            }
        }
    }

    public void cancelCheck(int position) {
        MultipleItemEntity entity = getItem(position);
        if (entity != null) {
            entity.setField("cancelable", false);
            entity.setField("checked", false);
            if (mCheckedList != null) {
                mCheckedList.remove(entity);
            }
            notifyItemChanged(position);
        }
    }

    public interface OnCancelListener {
        void onCancel(MultipleItemEntity entity, int position);
    }
}
